package xyz.missou.blog.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import xyz.missou.blog.entity.*;
import xyz.missou.blog.service.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;

@Controller
@RequestMapping("/article")
public class ArticleController extends BaseController{

    @Resource
    private ArticleService articleService;
    @Resource
    private CommentService commentService;
    @Resource
    private TagService tagService;


    @RequestMapping({"/{article_id}/","/{article_id}"})
    public String article(HttpServletRequest request,HttpSession session, Model model,@PathVariable("article_id") Integer article_id){
        HashSet<Integer> readArticleIds= (HashSet<Integer>)session.getAttribute("readArticleIds");
        if (readArticleIds==null){
            readArticleIds=new HashSet<Integer>();
            session.setAttribute("readArticleIds",readArticleIds);
        }
        if (!readArticleIds.contains(article_id)){
            articleService.pageViewUpdate(article_id);
            readArticleIds.add(article_id);
            session.setAttribute("readArticleIds",readArticleIds);
        }
        Article article=articleService.getArticleById(article_id);
        ArrayList<Comment> comments=commentService.getArticleComments(article_id);
        ArrayList<Tag> tags=tagService.getArticleTags(article_id);
        model.addAttribute("article",article);
        model.addAttribute("comments",comments);
        model.addAttribute("tags",tags);
        return view("article");
    }

    @RequestMapping({"/{article_id}/addcomment/","/{article_id}/addcomment"})
    @ResponseBody
    public String addComment(HttpSession session,@PathVariable("article_id") Integer article_id,String content){
        User user=(User) session.getAttribute("user");
        Article article=articleService.getArticleById(article_id);
        if (user==null || article==null){
            return "NO";
        }else{
            Comment comment=new Comment();
            comment.setArticle(article);
            comment.setContent(content);
            comment.setCreateTime(new Date());
            comment.setUser(user);
            commentService.addComment(comment);
            return "OK";
        }
    }
}
